package cn.chinaflame.pagodas.web;

import javax.servlet.http.HttpServletRequest;

import cn.chinaflame.pagodas.entity.PaOrderitem;
import cn.chinaflame.pagodas.repository.PaOrderitemRepository;
import cn.chinaflame.pagodas.service.*;
import cn.chinaflame.pagodas.vo.LightVO;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import cn.chinaflame.pagodas.Result.Result;
import cn.chinaflame.pagodas.dto.PaOrderDto;
import cn.chinaflame.pagodas.enums.CodeEnum;
import cn.chinaflame.pagodas.req.CallbackPaydataReq;
import cn.chinaflame.pagodas.req.PaHeadReq;
import cn.chinaflame.pagodas.req.PaydataReq;
import cn.chinaflame.pagodas.utils.DateTimes;
import cn.chinaflame.pagodas.utils.MemberBalance;
import cn.chinaflame.pagodas.utils.ParamPreconditions;

import java.math.BigDecimal;
import java.util.List;

/**
* @author    created by lbq
* @date	     2018年7月19日 下午4:29:24
**/
@RestController
@Transactional(rollbackFor = Exception.class)
@RequestMapping(value = "openapi/v1/pagodas/js/")
public class OpenPayJsApi {
	private static final Logger log = LoggerFactory.getLogger(OpenPayJsApi.class);
	@Autowired
	private PayJsApiService payJsApiService;
	@Autowired
	private YwPayApiService ywPayApiService;
	@Autowired
	private PaOrderService paOrderService;
	@Autowired
	private PaMemberService paMemberService;
	@Autowired
	private PaProductPointService paProductPointService;
	@Autowired
	private PaOrderitemRepository paOrderitemRepository;
	
	/**
	 * 佛龛清结算微信支付（jsapi）
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@PostMapping("pay")
	public Object JsApiPay(@RequestBody PaHeadReq req) throws Exception{
		req.check();
		String result= (String) payJsApiService.JsApi(req);
		ParamPreconditions.checkNotEmpty(result, CodeEnum.FAIL.getCode(), "请求支付失败，请联系工程师");
		return Result.create("OK", result);
	}
	/**
	 * 佛龛接收清结算后台通知
	 * @param request
	 * @return
	 */
	@RequestMapping("noticeUrl")
	@ResponseBody
	public String noticeUrl(HttpServletRequest request){
		payJsApiService.notifyBkgUrl(request);
		return "OK";
	}
	
	
	
	/**
	 * 佛龛炎武微信支付（jsapi）
	 * @param req
	 * @return
	 * @throws Exception
	 */
	@PostMapping("yanwu/pay")
	public Object YwJsApiPay(@RequestBody PaydataReq req) throws Exception{
		log.info("支付接口 req:{}",req);
		req.check();
		//ParamPreconditions.checkNotEmpty(result, CodeEnum.FAIL.getCode(), "请求支付失败，请联系工程师");
		return ywPayApiService.WxPay(req);
	}
	/**
	 * 佛龛接收后台通知
	 * @param
	 * @return
	 */
	@RequestMapping("yanwu/noticeUrl")
	@ResponseBody
	public String updateYwOrder(String merchantId, String version, String paymentOrderId,String orderNo, String orderDatetime,
			String orderAmount, String payDatetime, String payAmount, String payResult, String returnDatetime) {
		log.info("佛龛订单支付回调接口orderNo:{},paymentOrderId:{},orderAmount:{}",orderNo,paymentOrderId,orderAmount);
		CallbackPaydataReq req = new CallbackPaydataReq();
		req.setOrderNo(orderNo);
		req.setPaymentOrderId(paymentOrderId);
		BigDecimal amount = new BigDecimal(payAmount);
		req.setPayAmount(amount.divide(new BigDecimal("100")).toString());
		req.setPayResult("1");
		PaOrderDto pd = paOrderService.orderUpdate(req);
		//更改会员消费金额和最后消费时间
        MemberBalance.memberBalance(paMemberService, pd.getMemberId(), String.valueOf(pd.getMoney()), DateTimes.nowDateTime());
//		List<PaOrderitem> orderList = paOrderitemRepository.findByOrderId(pd.getId());
//        JSONArray param = new JSONArray();
//		JSONObject p = new JSONObject();
//		p.put("lightno", orderList.get(0).getLocationNo());
//		p.put("obj", orderList.get(0).getBeWishedName());
//		p.put("bless", orderList.get(0).getBeWishedMemo());
//		param.add(p);
//		paProductPointService.lightCheckAndSend(param);
        return "SUCCESS";
	}
	
}
